<template>
  <div class="departments-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>部门管理</h2>
      <el-button type="primary" @click="openAddDialog" :disabled="!canDeptOperate()">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </div>

    <!-- 部门列表 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header">
          <span>部门列表</span>
          <div class="table-actions">
            <el-button size="small" @click="fetchDepartments">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      <el-table :data="pagedDepartments" v-loading="loading" style="width: 100%">
        <el-table-column prop="departName" label="部门名称" min-width="180" />
        <el-table-column prop="parentName" label="上级部门" min-width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)" :disabled="!canDeptOperate()">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-tooltip v-if="row.hasChildren" content="请先删除该部门的所有子部门" placement="top">
              <el-button size="small" type="danger" :disabled="true">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-tooltip>
            <el-button
              v-else
              size="small"
              type="danger"
              @click="handleDelete(row)"
              :loading="deleteLoadingId === row.id"
              :disabled="!canDeptOperate()"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="departments.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="editMode ? '编辑部门' : '新增部门'" v-model="dialogVisible" width="400px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="部门名称" prop="departName">
          <el-input v-model="form.departName" maxlength="32" show-word-limit />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentID">
          <el-select v-model="form.parentID" placeholder="无（顶级部门）" clearable style="width: 100%">
            <el-option v-for="d in departments" :key="d.id" :label="d.departName" :value="d.id" :disabled="d.id === form.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import departmentAPI from '@/api/department'
import { useUserStore } from '@/stores/user'

const departments = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const editMode = ref(false)
const form = reactive({ departName: '', parentID: null, id: null })
const formRef = ref()
const submitLoading = ref(false)
const deleteLoadingId = ref(null)
const pagination = reactive({ current: 1, size: 10 })

const rules = {
  departName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 32, message: '长度2-32个字符', trigger: 'blur' }
  ]
}

const pagedDepartments = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  const end = start + pagination.size
  return departments.value.slice(start, end)
})

const userStore = useUserStore()
const currentRole = computed(() => {
  const info = userStore.userInfo || {}
  if (Array.isArray(info.roles) && info.roles.length > 0) return info.roles[0]
  return info.role || 'User'
})
const canDeptOperate = () => currentRole.value === 'Boss'

async function fetchDepartments() {
  loading.value = true
  try {
    const response = await departmentAPI.getDepartments()
    if (response.code === 200 && Array.isArray(response.value)) {
      // 兼容字段
      const list = response.value.map(item => ({
        id: item.ID || item.id,
        departName: item.DepartName || item.departName,
        parentID: item.ParentID || item.parentID,
        parentName: ''
      }))
      // 处理上级部门名称
      list.forEach(dep => {
        if (dep.parentID) {
          const parent = list.find(d => d.id === dep.parentID)
          dep.parentName = parent ? parent.departName : ''
        }
      })
      // 标记有子部门的节点
      list.forEach(dep => {
        dep.hasChildren = list.some(d => d.parentID === dep.id)
      })
      departments.value = list
    } else {
      ElMessage.error(response.msg || '获取部门列表失败')
      departments.value = []
    }
  } catch (error) {
    ElMessage.error('获取部门列表失败')
    departments.value = []
  } finally {
    loading.value = false
  }
}

function openAddDialog() {
  if (!canDeptOperate()) {
    ElMessage.error('权限不足')
    return
  }
  editMode.value = false
  form.departName = ''
  form.parentID = null
  form.id = null
  dialogVisible.value = true
}

function openEditDialog(row) {
  if (!canDeptOperate()) {
    ElMessage.error('权限不足')
    return
  }
  editMode.value = true
  form.departName = row.departName
  form.parentID = row.parentID
  form.id = row.id
  dialogVisible.value = true
}

function submitForm() {
  formRef.value.validate(async valid => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (editMode.value) {
        await departmentAPI.updateDepartment(form.id, {
          departmentName: form.departName,
          parentID: form.parentID
        })
        ElMessage.success('修改成功')
        await userStore.refreshUserInfo()
      } else {
        await departmentAPI.addDepartment({
          departmentName: form.departName,
          parentID: form.parentID
        })
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchDepartments()
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

function handleDelete(row) {
  if (!canDeptOperate()) {
    ElMessage.error('权限不足')
    return
  }
  if (row.hasChildren) {
    ElMessage.warning('请先删除该部门的所有子部门')
    return
  }
  ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      deleteLoadingId.value = row.id
      try {
        await departmentAPI.deleteDepartment(row.id)
        ElMessage.success('删除成功')
        await userStore.refreshUserInfo()
        fetchDepartments()
      } catch (error) {
        ElMessage.error('删除失败')
      } finally {
        deleteLoadingId.value = null
      }
    })
}

onMounted(fetchDepartments)
</script>

<style scoped>
.departments-container {
  padding: 32px 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px #f0f1f2;
  border: none;
  margin-bottom: 24px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}
.table-actions {
  display: flex;
  gap: 8px;
}
.pagination-wrapper {
  margin: 16px 0 0 0;
  display: flex;
  justify-content: flex-end;
}
</style>
